import { NextResponse } from 'next/server'
import fs from 'fs/promises'
import path from 'path'

export async function GET() {
  try {
    const configPath = path.join(process.cwd(), 'config.json')
    let config = { 
      openai: { baseURL: '', apiKey: '' },
      serviceUrl: '',
      licenseKey: ''
    }
    
    try {
      const fileContent = await fs.readFile(configPath, 'utf-8')
      config = JSON.parse(fileContent)
    } catch (error) {
      if (error.code !== 'ENOENT') {
        throw error
      }
    }
    
    return NextResponse.json(config, { status: 200 })
  } catch (error) {
    console.error('获取配置出错:', error)
    return NextResponse.json(
      { message: '获取配置失败' },
      { status: 500 }
    )
  }
}

export async function POST(request: Request) {
  try {
    const { apiKey, apiEndpoint, serviceUrl,licenseKey } = await request.json()

    if (!apiKey || !apiEndpoint) {
      return NextResponse.json(
        { message: 'API Key和API Endpoint是必填项' },
        { status: 400 }
      )
    }

    const configPath = path.join(process.cwd(), 'config.json')
    let config = { 
      openai: { baseURL: '', apiKey: '' },
      serviceUrl: '',
      licenseKey: ''
    }
    
    try {
      const fileContent = await fs.readFile(configPath, 'utf-8')
      config = JSON.parse(fileContent)
    } catch (error) {
      if (error.code !== 'ENOENT') {
        throw error
      }
    }
    
    config.openai = {
      ...config.openai,
      baseURL: apiEndpoint,
      apiKey: apiKey
    }
    
    if (serviceUrl) {
      config.serviceUrl = serviceUrl
    }
    if (licenseKey) {
      config.licenseKey = licenseKey
    }
    
    await fs.writeFile(configPath, JSON.stringify(config, null, 2))

    return NextResponse.json(
      { message: '配置保存成功' },
      { status: 200 }
    )
  } catch (error) {
    console.error('保存配置出错:', error)
    return NextResponse.json(
      { message: '保存配置失败' },
      { status: 500 }
    )
  }
}